package com.alm.token.ui.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.R;
import com.alm.token.apinew.LogInterceptor;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.Info;
import com.alm.token.ui.data.bean.MiningWalletTypeIndexData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.StakingMiningMoneyDrawIndexData;
import com.alm.token.ui.data.bean.StakingOrderAddData;
import com.alm.token.ui.data.bean.StakingOrderAppendData;
import com.alm.token.ui.data.bean.StakingOrderIndexData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.StakingView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import baibeiwallet.Constant;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class StakingOrderCloseNewActivity extends BaseActivity implements StakingView<StakingOrderIndexData> {


    @BindView(R.id.tv_orderLevel1)
    TextView tvOrderLevel1;
    @BindView(R.id.ly_xinjibody1)
    LinearLayout lyXinjibody1;
    @BindView(R.id.tv_impawnmoney)
    TextView tvImpawnmoney;
    @BindView(R.id.tv_impawn_miovalue)
    TextView tvImpawnMiovalue;
    @BindView(R.id.rly_impawnbody)
    RelativeLayout rlyImpawnbody;
    @BindView(R.id.tv_order_continuedDay)
    TextView tvOrderContinuedDay;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.rly_selectmoney_item)
    RelativeLayout rlySelectmoneyItem;
    @BindView(R.id.tv_mostinput)
    TextView tvMostinput;
    @BindView(R.id.rly_mostinputmoney)
    RelativeLayout rlyMostinputmoney;
    @BindView(R.id.tv_tv1)
    TextView tvTv1;
    @BindView(R.id.edt_inputmoney)
    EditText edtInputmoney;
    @BindView(R.id.tv_miovalue)
    TextView tvMiovalue;
    @BindView(R.id.rly_inputbody)
    RelativeLayout rlyInputbody;
    @BindView(R.id.tv_order_append_totle)
    TextView tvOrderAppendTotle;
    @BindView(R.id.tv_yuyueorderLevel)
    TextView tvYuyueorderLevel;
    @BindView(R.id.ly_yuyuexinjibody)
    LinearLayout lyYuyuexinjibody;
    @BindView(R.id.tv_order_yuyuezhouqi)
    TextView tvOrderYuyuezhouqi;
    @BindView(R.id.tv_order_yuyueyuehua)
    TextView tvOrderYuyueyuehua;
    @BindView(R.id.ly_yuyueorderbody)
    LinearLayout lyYuyueorderbody;
    @BindView(R.id.tv_order_shenfen)
    TextView tvOrderShenfen;
    @BindView(R.id.tv_order_shouxubili)
    TextView tvOrderShouxubili;
    @BindView(R.id.tv_order_shouxu)
    TextView tvOrderShouxu;
    @BindView(R.id.tv_shouxu_more)
    TextView tvShouxuMore;
    @BindView(R.id.rly_shouxu_item)
    RelativeLayout rlyShouxuItem;
    @BindView(R.id.ly_userRolebody)
    LinearLayout lyUserRolebody;
    @BindView(R.id.btn_quantitativeapply_click)
    TextView btnQuantitativeapplyClick;
    @BindView(R.id.btn_quantitativeapply_appendclick)
    TextView btnQuantitativeapplyAppendclick;
    @BindView(R.id.btn_quantitativeapply_closeclick)
    TextView btnQuantitativeapplyCloseclick;
    @BindView(R.id.ly_bottom)
    LinearLayout lyBottom;

    private List<StakingOrderIndexData.DataBean.OrderBean.AppendListBean> appendList;
    private StakingOrderIndexData.DataBean data;
    private StakingOrderIndexData.DataBean.WaitObjBean waitObj;
    private StakingOrderIndexData.DataBean.UserRoleBean userRole;
    private List<StakingOrderIndexData.DataBean.GoodsBean> goods;
    private StakingOrderIndexData.DataBean.OrderBean order;
    private StakingOrderIndexData.DataBean.OrderBean.PayOrderVoBean payOrderVo;
    private int moneyType;
    private String orderSn;
    private double mioWallet, mioPrice, number;

    List<StakingOrderIndexData.DataBean.OrderBean.TypeOrderVosBean> typeOrderVos = new ArrayList<>();
    StakingOrderIndexData.DataBean.OrderBean.TypeOrderVosBean typeOrderVosBean;

    public StakingOrderCloseNewActivity() {
    }

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_staking_orderclosenew;
    }

    @Override
    protected void initVariables() {
        moneyType = getIntent().getIntExtra("moneyType", 0);
        orderSn = getIntent().getStringExtra("orderSn");
    }


    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.staking_hint_closetitle));
        initManager();
    }

    private void initManager() {

    }

    @Override
    protected void loadData() {
        preenter.getStakingOrderIndexData(String.valueOf(moneyType), orderSn);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rightItem:
//                startActivity(LH2OrderHistoryActivity.class);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == ActivityForResultCode) {
//            if (resultCode == QuantitativeOrderOpenAddActivity.AddAppendSucc) {
////                showToast("添加成功，刷新列表");
//                loadData();
//                setResult(QuantitativeOrderOpenAddActivity.AddAppendSucc);
////                finish();
//            }
//            if (resultCode == QuantitativeOrderDetailActivity.AppendSucc) {
////                showToast("添加成功，刷新列表");
//                loadData();
//                setResult(QuantitativeOrderDetailActivity.AppendSucc);
////                finish();
//            }
//        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void getData(StakingOrderIndexData stakingOrderIndexData) {
        if (stakingOrderIndexData.getStatus() == 0) {
            data = stakingOrderIndexData.getData();
            if (EmptyUtils.isNotEmpty(data)) {
                // 订单处于待支付，排队中 或 为null
                waitObj = data.getWaitObj();
                // 当订单可关闭时
                userRole = data.getUserRole();
                // 可选择的套餐 当order 不为null时有数据
                goods = data.getGoods();

                // order 不为null 有已预约订单
                order = data.getOrder();
            }

//            if (EmptyUtils.isNotEmpty(order) && EmptyUtils.isNotEmpty(userRole) && order.getStatus() == 3) {
//                lyUserRolebody.setVisibility(View.VISIBLE);
//                tvOrderShenfen.setText(userRole.getUserRole());
//                tvOrderShouxubili.setText(userRole.getTakeOffRatio() + "%");
//                tvOrderShouxu.setText(userRole.getCloseServiceCharge() + "MIO");
//            } else {
            lyUserRolebody.setVisibility(View.GONE);
//            }

//            mioWallet = data.getMioWallet();
            mioPrice = data.getMioPrice();
            tvMiovalue.setText(getString(R.string.staking_hint_mostclose) + mioWallet + "MIO");
            edtInputmoney.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (s.toString().contains(".")) {
                        if (s.length() - 1 - s.toString().indexOf(".") > 4) {
                            s = s.toString().subSequence(0, s.toString().indexOf(".") + 5);
                            edtInputmoney.setText(s);
                            edtInputmoney.setSelection(s.length());
                        }
                    }
                    if (s.toString().trim().substring(0).equals(".")) {
                        s = "0" + s;
                        edtInputmoney.setText(s);
                        edtInputmoney.setSelection(2);
                    }

                    if (s.toString().startsWith("0")
                            && s.toString().trim().length() > 1) {
                        if (!s.toString().substring(1, 2).equals(".")) {
                            edtInputmoney.setText(s.subSequence(0, 1));
                            edtInputmoney.setSelection(1);
                            return;
                        }
                    }

                    number = Double.parseDouble(s != null ? (!s.toString().isEmpty() ? s.toString() : "0") : "0");

                    if (number > mioWallet * mioPrice) {
                        showToast(getString(R.string.conversioncurrency_hint1_warn6));
                        edtInputmoney.setText("");
                        return;
                    }
                    mathNumber();
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

            rlyInputbody.setVisibility(View.VISIBLE);

            if (EmptyUtils.isNotEmpty(order)) {

                // 可追加币种
                appendList = order.getAppendList();

                typeOrderVos = order.getTypeOrderVos();
                if (EmptyUtils.isNotEmpty(typeOrderVos)) {
                    typeOrderVosBean = typeOrderVos.get(0);
                    tvSelect.setText(typeOrderVosBean.getMoneyTypeStr());
                    moneyType = typeOrderVosBean.getMoneyType();
                    mioWallet = Double.valueOf(typeOrderVosBean.getPayMio());
                    tvMiovalue.setText(getString(R.string.staking_hint_mostclose) + mioWallet + "MIO");

                    if (EmptyUtils.isNotEmpty(appendList)) {

                        for (StakingOrderIndexData.DataBean.OrderBean.TypeOrderVosBean
                                typeOrderVosBean : typeOrderVos) {

                            for (StakingOrderIndexData.DataBean.OrderBean.AppendListBean
                                    appendListBean : appendList) {
                                if (typeOrderVosBean.getMoneyTypeStr()
                                        .equalsIgnoreCase(appendListBean.getName())) {
                                    typeOrderVosBean.setUrl(appendListBean.getUrl());
                                    break;
                                }
                            }
                        }
                    }
                }


                orderSn = order.getOrderSn();
                rlyImpawnbody.setVisibility(View.VISIBLE);
                tvOrderContinuedDay.setText(order.getOpeningDays() + getString(R.string.lh20_hint_day));

                tvOrderLevel1.setText(order.getLevelName());
                int ll1 = order.getLevel();
                if (ll1 <= lyXinjibody1.getChildCount()) {
                    for (int i = 0; i < lyXinjibody1.getChildCount(); i++) {//4number  i=0-3
                        if (i < ll1) { //i=0 1 2 3  ll1=1 2 3 4
                            lyXinjibody1.getChildAt(i).setVisibility(View.VISIBLE);
                        } else {
                            lyXinjibody1.getChildAt(i).setVisibility(View.GONE);
                        }
                    }
                }

            } else {
                rlyImpawnbody.setVisibility(View.GONE);
            }
            edtInputmoney.setText("");
            if (EmptyUtils.isNotEmpty(timer)) {
                timer.cancel();
            }
            btnQuantitativeapplyClick.setVisibility(View.VISIBLE);
        } else {
            showToast(stakingOrderIndexData.getMsg());
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EmptyUtils.isNotEmpty(timer)) {
            timer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EmptyUtils.isNotEmpty(timer)) {
            timer.cancel();
            timer = null;
        }
    }

    private CountDownTimer timer;
    private long times = 0, refreshTime = -1;

    private void startTimer() {
        times = order.getActivationTime();
        timer = new CountDownTimer(times * 1000, 1000) {
            /**
             * 固定间隔被调用,就是每隔countDownInterval会回调一次方法onTick
             * @param millisUntilFinished
             */
            @Override
            public void onTick(long millisUntilFinished) {
//                tvPayTime.setText(formatSeconds(millisUntilFinished / 1000));//结束倒计时
            }

            /**
             * 倒计时完成时被调用
             */
            @Override
            public void onFinish() {
                if (EmptyUtils.isNotEmpty(preenter)) {
                    loadData();
                }
//                        tv_remaining_time.setText("00:00");
            }
        };
        if (times != 0) {
            timer.start();
        }
    }

    Map<Integer, Double> valueMaps = new HashMap<>();

    private void mathNumber() {
        valueMaps.clear();
        valueMaps.put(moneyType, number);
        tvImpawnmoney.setText("≈ " + "$" + CommonUtil.saveToPoint2WithNo(order.getMoney() - number));

        tvImpawnMiovalue.setText(CommonUtil.saveToPoint4WithNo(number / mioPrice) + "MIO");

        tvOrderAppendTotle.setText(CommonUtil.saveToPoint4WithNo4((order.getMoney() - number) / mioPrice) + "MIO");

        if (EmptyUtils.isNotEmpty(goods)) {
            for (int j = goods.size() - 1; j >= 0; j--) {

                if (order.getMoney() - number >= goods.get(j).getGoodsValue()) {
                    int ll1 = j + 1;
                    if (ll1 <= lyYuyuexinjibody.getChildCount()) {
                        for (int i = 0; i < lyYuyuexinjibody.getChildCount(); i++) {//4number  i=0-3
                            if (i < ll1) { //i=0 1 2 3  ll1=1 2 3 4
                                lyYuyuexinjibody.getChildAt(i).setVisibility(View.VISIBLE);
                            } else {
                                lyYuyuexinjibody.getChildAt(i).setVisibility(View.GONE);
                            }
                        }
                    }
                    tvYuyueorderLevel.setText("STKL" + goods.get(j).getLevel());//goods.get(j).getGoodsName()
                    tvOrderYuyueyuehua.setText(goods.get(j).getMonthlyEarnings() + "%/" + getString(R.string.alphago_hint_month));
                    tvOrderYuyuezhouqi.setText(goods.get(j).getCycle() + getString(R.string.lh20_hint_day));
                    lyYuyueorderbody.setVisibility(View.VISIBLE);
                    break;
                } else {
                    lyYuyueorderbody.setVisibility(View.GONE);
                }
            }
//            if (number != 0) {
//                lyYuyueorderbody.setVisibility(View.VISIBLE);
//            } else {
//                lyYuyuexinjibody.setVisibility(View.GONE);
//            }
        }
        if (order.getMoney() - number < 100) {
            showToast(getString(R.string.staking_hint_closesomewarm));
            edtInputmoney.setText("");
        }
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast("需要重新登录!");
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(getActivity(),PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            getActivity().finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    @OnClick({R.id.btn_quantitativeapply_click, R.id.btn_quantitativeapply_appendclick, R.id.btn_quantitativeapply_closeclick
            , R.id.tv_mostinput, R.id.tv_select})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_select:
                if (EmptyUtils.isNotEmpty(typeOrderVos)) {
                    showPopwindow();
                }
                break;
            case R.id.tv_mostinput:
                edtInputmoney.setText(String.valueOf(mioWallet * mioPrice - (mioWallet * mioPrice % 100)));
                break;
            case R.id.btn_quantitativeapply_click:
                //开启  输入100的整数倍
                if (number <= 0 || number % 100 != 0) {
                    showToast(getString(R.string.staking_hint_closewarm));
                    break;
                }

                Info info = new Info();/*** 利用Gson 将对象转json字符串*/
                info.setOrderSn(orderSn);
                List<Info.MoneyTypesBean> moneyTypes = new ArrayList<>();
                if (EmptyUtils.isNotEmpty(valueMaps)) {
                    for (int key : valueMaps.keySet()) {
                        if (valueMaps.get(key) != 0) {
                            Info.MoneyTypesBean moneyTypesBean = new Info.MoneyTypesBean();
                            moneyTypesBean.setMoney(String.valueOf(valueMaps.get(key)));
                            moneyTypesBean.setMoneyType(String.valueOf(key));
                            moneyTypes.add(moneyTypesBean);
                        }
                    }
                }
                if (EmptyUtils.isNotEmpty(moneyTypes)) {
                    info.setMoneyTypes(moneyTypes);
                }
                Gson gson = new Gson();
                String jsonData = gson.toJson(info);

                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonData);
                LogInterceptor.Content_Type_Json = "application/json";
                preenter.getStakingCloseOrderByMoneyData(body);
                break;
            case R.id.btn_quantitativeapply_appendclick:


                break;
            case R.id.btn_quantitativeapply_closeclick:


                break;

        }


    }

    PopupWindow popWindow;

    private void showPopwindow() {


        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.view_pop_selecter, null);
        LinearLayout ly_pop_body = popView.findViewById(R.id.ly_pop_body);

        if (EmptyUtils.isNotEmpty(typeOrderVos)) {
            for (int i = 0; i < typeOrderVos.size(); i++) {
                StakingOrderIndexData.DataBean.OrderBean.TypeOrderVosBean coinBean = typeOrderVos.get(i);
                if (!coinBean.getMoneyTypeStr().equalsIgnoreCase(Constant.G12ContractName)) {
                    View itemView = View.inflate(this, R.layout.item_pop_wallet, null);
//                    ImageView imageView = (ImageView) itemView.findViewById(R.id.img_bizhongicon);
//                    imageView.setVisibility(View.GONE);

                    GlideApp.with(this)
                            .load(coinBean.getUrl())
                            .error(R.drawable.icon_arctic)
                            .into((ImageView) itemView.findViewById(R.id.img_bizhongicon));
                    ((TextView) itemView.findViewById(R.id.name)).setText(coinBean.getMoneyTypeStr());
                    ((TextView) itemView.findViewById(R.id.desc)).setVisibility(View.INVISIBLE);

                    ((TextView) itemView.findViewById(R.id.money1)).setText("$" + CommonUtil.saveToPoint2WithNo(Double.parseDouble(coinBean.getDollar())));
                    ((TextView) itemView.findViewById(R.id.money2)).setText(coinBean.getPayMio() + "MIO");

                    int finalI = i;
                    itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            typeOrderVosBean = typeOrderVos.get(finalI);
                            mioWallet = Double.valueOf(typeOrderVosBean.getPayMio());
                            tvMiovalue.setText(getString(R.string.staking_hint_mostclose) + mioWallet + "MIO");

                            moneyType = typeOrderVosBean.getMoneyType();
                            tvSelect.setText(typeOrderVosBean.getMoneyTypeStr());
                            number = 0;
                            edtInputmoney.setText("");
                            mathNumber();
                            popWindow.dismiss();
                        }
                    });
                    ly_pop_body.addView(itemView);
                }
            }
            ly_pop_body.setBackgroundColor(getResources().getColor(R.color.text_cccccc));
        }

        RelativeLayout outside = popView.findViewById(R.id.pop_outside);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        if (popWindow == null) {
            popWindow = new PopupWindow(popView, width, height);
            popWindow.setAnimationStyle(R.style.BottomToTopAnim);
//        popWindow.setFocusable(true);
            popWindow.setOutsideTouchable(true);// 设置同意在外点击消失
        }
        outside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void getStakingAddOrderData(StakingOrderAddData stakingOrderAddData) {
        if (stakingOrderAddData.getStatus() == 0) {
            orderSn = stakingOrderAddData.getData().getOrderSn();
            setResult(QuantitativeOrderDetailActivity.AppendSucc);
            edtInputmoney.setText("");
            loadData();
        } else {
            showToast(stakingOrderAddData.getMsg());
        }
    }

    @Override
    public void getStakingCancelQueuingData(RegisterData registerData) {

    }

    @Override
    public void getStakingPayOrderData(RegisterData registerData) {
        showToast(registerData.getMsg());
        if (registerData.getStatus() == 0) {
            setResult(QuantitativeOrderDetailActivity.AppendSucc);
            loadData();
        }
    }

    @Override
    public void getStakingOrderAppendData(StakingOrderAppendData appendData) {

        if (appendData.getStatus() == 0) {
            DialogUtils.enterPayPsw(this, (pwd1) -> {
                //eth1 mio2
                preenter.getStakingPayOrderData(appendData.getData().getOrderSn(), pwd1);
            });
        } else {
            showToast(appendData.getMsg());
        }
    }

    @Override
    public void getStakingMiningMoneyDrawIndexData(StakingMiningMoneyDrawIndexData stakingMiningMoneyDrawIndexData) {

    }

    @Override
    public void getMiningWalletTypeIndexData(MiningWalletTypeIndexData miningWalletTypeIndexData) {

    }

    @Override
    public void getDrawIndexData(Object o) {

    }
}
